<!DOCTYPE html>
<html lang="en">

<!-- Head tag -->
<head><meta name="generator" content="Hexo 3.9.0">
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="google-site-verification" content="xBT4GhYoi5qRD5tr338pgPM5OWHHIDR6mNg1a3euekI">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content>
    <meta name="keyword" content>
    <link rel="shortcut icon" href="/myblog/img/favicon.ico">

    <title>
        
          jvm GC收集器 - Ethan的博客 | Ethan&#39;s Blog
        
    </title>

    <link rel="canonical" href="http://reflectyi.gitee.io/myblog/myblog/2016/10/01/jvm/memory/GC收集器7种/">

    <!-- Bootstrap Core CSS -->
    <link rel="stylesheet" href="/myblog/css/bootstrap.min.css">

    <!-- Custom CSS -->
    <link rel="stylesheet" href="/myblog/css/hux-blog.min.css">

    <!-- Pygments Highlight CSS -->
    <link rel="stylesheet" href="/myblog/css/highlight.css">

    <!-- Custom Fonts -->
    <!-- <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css" rel="stylesheet" type="text/css"> -->
    <!-- Hux change font-awesome CDN to qiniu -->
    <link href="https://cdn.staticfile.org/font-awesome/4.5.0/css/font-awesome.min.css" rel="stylesheet" type="text/css">


    <!-- Hux Delete, sad but pending in China
    <link href='http://fonts.googleapis.com/css?family=Lora:400,700,400italic,700italic' rel='stylesheet' type='text/css'>
    <link href='http://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800' rel='stylesheet' type='text/
    css'>
    -->


    <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
    <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
    <!--[if lt IE 9]>
        <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
        <script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
    <![endif]-->

    <!-- ga & ba script hoook -->
    <script></script>
</head>


<!-- hack iOS CSS :active style -->
<body ontouchstart="">

    <!-- Navigation -->
<nav class="navbar navbar-default navbar-custom navbar-fixed-top">
    <div class="container-fluid">
        <!-- Brand and toggle get grouped for better mobile display -->
        <div class="navbar-header page-scroll">
            <button type="button" class="navbar-toggle">
                <span class="sr-only">Toggle navigation</span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
            </button>
            <a class="navbar-brand" href="/myblog/">Hi,Ethan</a>
        </div>

        <!-- Collect the nav links, forms, and other content for toggling -->
        <!-- Known Issue, found by Hux:
            <nav>'s height woule be hold on by its content.
            so, when navbar scale out, the <nav> will cover tags.
            also mask any touch event of tags, unfortunately.
        -->
        <div id="huxblog_navbar">
            <div class="navbar-collapse">
                <ul class="nav navbar-nav navbar-right">
                    <li>
                        <a href="/myblog/">首页</a>
                    </li>

                    

                        
                    

                        
                        <li>
                            <a href="/myblog/about/">目录</a>
                        </li>
                        
                    

                        
                        <li>
                            <a href="/myblog/archives/">时间轴</a>
                        </li>
                        
                    

                        
                        <li>
                            <a href="/myblog/tags/">标签</a>
                        </li>
                        
                    
                    
                </ul>
            </div>
        </div>
        <!-- /.navbar-collapse -->
    </div>
    <!-- /.container -->
</nav>
<script>
    // Drop Bootstarp low-performance Navbar
    // Use customize navbar with high-quality material design animation
    // in high-perf jank-free CSS3 implementation
    var $body   = document.body;
    var $toggle = document.querySelector('.navbar-toggle');
    var $navbar = document.querySelector('#huxblog_navbar');
    var $collapse = document.querySelector('.navbar-collapse');

    $toggle.addEventListener('click', handleMagic)
    function handleMagic(e){
        if ($navbar.className.indexOf('in') > 0) {
        // CLOSE
            $navbar.className = " ";
            // wait until animation end.
            setTimeout(function(){
                // prevent frequently toggle
                if($navbar.className.indexOf('in') < 0) {
                    $collapse.style.height = "0px"
                }
            },400)
        }else{
        // OPEN
            $collapse.style.height = "auto"
            $navbar.className += " in";
        }
    }
</script>


    <!-- Main Content -->
    
<!-- Image to hack wechat -->
<!-- <img src="http://reflectyi.gitee.io/myblog/myblog/img/icon_wechat.png" width="0" height="0"> -->
<!-- <img src="{{ site.baseurl }}/{% if page.header-img %}{{ page.header-img }}{% else %}{{ site.header-img }}{% endif %}" width="0" height="0"> -->

<!-- Post Header -->
<style type="text/css">
    header.intro-header{
        background-image: url('/myblog/img/home-bg.jpg')
    }
</style>
<header class="intro-header" >
    <div class="container">
        <div class="row">
            <div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1">
                <div class="post-heading">
                    <div class="tags">
                        
                          <a class="tag" href="/myblog/tags/#jvm" title="jvm">jvm</a>
                        
                          <a class="tag" href="/myblog/tags/#GC" title="GC">GC</a>
                        
                    </div>
                    <h1>jvm GC收集器</h1>
                    <h2 class="subheading">jvm 中常用GC收集器，回收方式</h2>
                    <span class="meta">
                        Posted by Ethan on
                        2016-10-01
                    </span>
                </div>
            </div>
        </div>
    </div>
</header>

<!-- Post Content -->
<article>
    <div class="container">
        <div class="row">

    <!-- Post Container -->
            <div class="
                col-lg-8 col-lg-offset-2
                col-md-10 col-md-offset-1
                post-container">

                <h2 id="GC收集器"><a href="#GC收集器" class="headerlink" title="GC收集器"></a>GC收集器</h2><h3 id="概述"><a href="#概述" class="headerlink" title="概述"></a>概述</h3><ul>
<li><p>新生代(young generation)：</p>
<ul>
<li>Serial</li>
<li>ParNew</li>
<li>Parallel Scavenge </li>
</ul>
</li>
<li><p>老年代(Tenured generation)</p>
<ul>
<li>Serial Old</li>
<li>Parallel Old</li>
<li>CMS</li>
</ul>
</li>
<li>全部适用<ul>
<li>G1 </li>
</ul>
</li>
<li>没有最好的收集器，要根据实际情况进行相应的选择<h3 id="1、serial收集器"><a href="#1、serial收集器" class="headerlink" title="1、serial收集器"></a>1、serial收集器</h3></li>
<li>特点：<ul>
<li>复制算法  </li>
<li>单线程收集器，暂停所有工作线程(Stop-The-World)</li>
<li>简单高效(相对其他收集器的单线程而言)，没有交互开销</li>
<li>Client模式下虚拟机没有过多内存分配，Cpu核数较少的情况下，表现不错<h3 id="2、ParNew收集器"><a href="#2、ParNew收集器" class="headerlink" title="2、ParNew收集器"></a>2、ParNew收集器</h3></li>
</ul>
</li>
<li>特点：<ul>
<li>复制算法 </li>
<li>serial收集器的多线程版本</li>
<li>在Server模式下新生代收集器</li>
<li>多线程中唯一能配合CMS收集器使用(serial单线程也可以)</li>
<li>单核不如serial，双核不保证，多核情况下表现可以</li>
<li>默认线程数和CPU核数相同<h3 id="3、Parallel-Scavenge"><a href="#3、Parallel-Scavenge" class="headerlink" title="3、Parallel Scavenge"></a>3、Parallel Scavenge</h3></li>
</ul>
</li>
<li>特点：<ul>
<li>复制算法</li>
<li>多线程收集器 </li>
<li>达到可控制的吞吐量<ul>
<li>吞吐量=运行用户代码时间/(运行用户代码时间+)  </li>
</ul>
</li>
<li>高吞吐量可以高效利用CPU,适合后台应用</li>
<li>缩短GC的停顿时间，会降低吞吐量和减小新生代空间。</li>
<li>如果不设置参数，虚拟机可以自动收集性能监控，自动调节停顿时间和吞吐量大小<h3 id="4、serial-Old收集器"><a href="#4、serial-Old收集器" class="headerlink" title="4、serial Old收集器"></a>4、serial Old收集器</h3></li>
</ul>
</li>
<li>特点：<ul>
<li>标记-整理算法</li>
<li>老年代收集器</li>
<li>单线程</li>
<li>serial老年代版本</li>
<li>在jdk1.5以前与Parallel Scavengepehe，以及CMS备选方案<h3 id="5、Parallel-Old"><a href="#5、Parallel-Old" class="headerlink" title="5、Parallel Old"></a>5、Parallel Old</h3></li>
</ul>
</li>
<li>特点：<ul>
<li>标记-整理算法 </li>
<li>多线程</li>
<li>Parallel Scavenge的老年代版本(1.6出现)</li>
<li>这个组合完成了”吞吐量优先”<h3 id="6、CMS-Current-Mark-Sweep"><a href="#6、CMS-Current-Mark-Sweep" class="headerlink" title="6、CMS(Current Mark Sweep)"></a>6、CMS(Current Mark Sweep)</h3></li>
</ul>
</li>
<li>特点：<ul>
<li>唯一标记-清除算法收集器(划时代)</li>
<li>多线程</li>
<li>获取最短停顿时间为目标的收集器，并发收集，低停顿</li>
</ul>
</li>
<li><p>运行过程：</p>
<ul>
<li>初始标记<ul>
<li>stop-the-world，标记GC Roots能到达的对象，速度快 </li>
</ul>
</li>
<li>并发标记<ul>
<li>就是进行GC Roots Tracing的过程</li>
</ul>
</li>
<li>重新标记<ul>
<li>stop-the-world，修正并发标记阶段，程序继续运行，导致obj标记变动，比初始标记时间长，比并发标记时间短很多</li>
</ul>
</li>
<li><p>并发清除</p>
</li>
<li><p>两个并发阶段，都可以和用户线程一起工作，整体看，CMS内存回收过程是和用户线程并发执行。</p>
</li>
</ul>
</li>
<li>缺点：<ul>
<li>对CPU资源敏感<ul>
<li>并发占用CPU造成吞吐量降低。程序反应慢。</li>
<li>CMS默认启动(cpu+3)/4条线程，所以在cpu低核尤其是低于4核的情况下，CMS占用资源极其明显，用户程序执行缓慢</li>
</ul>
</li>
<li>无法处理浮动垃圾<ul>
<li>CMS并发清理，清理过程中，用户线程也在不停的产生垃圾。而这部分垃圾，CMS当次无法处理，只能留给下次。</li>
</ul>
</li>
<li>空间碎片<ul>
<li>当没有连续内存空间分配给大对象的时候，不得不提前触发一次Full GC<h3 id="7、G1收集器"><a href="#7、G1收集器" class="headerlink" title="7、G1收集器"></a>7、G1收集器</h3></li>
</ul>
</li>
</ul>
</li>
<li>特点：<ul>
<li>面向服务端垃圾收集器</li>
<li>并行与并发。充分发挥多核优势缩短Stop-The-World时间。</li>
<li>分代收集。不需要其他收集器配合，能独立管理整个堆。能根据不同情况采用不同算法</li>
<li>空间整合<ul>
<li>整体看是标记-整理算法，局部看是复制算法</li>
<li>在这两种算法都能提供连续空间，为大对象分配，不用在触发GC</li>
</ul>
</li>
<li>可预测停顿时间<ul>
<li>和CMS比的另外一个优势，G1建立了可预测的时间停顿模型。</li>
<li>允许设置M毫秒的时间片段，GC停顿不能超过M毫秒 </li>
</ul>
</li>
</ul>
</li>
<li>G1在整体内存结构上并没有区分新生代和老年代。<ul>
<li>将整个堆，划分成了多个大小相等的区域(小区域划分新生代和老年代)，而不是和以前的收集器一样进行物理隔离。</li>
<li>每个region中都有对应的rememberSet</li>
</ul>
</li>
<li>G1建立可预测的停顿时间模型<ul>
<li>避免整个java堆垃圾收集</li>
<li>根据各个Region中，垃圾回收价值(获得空间大小和回收所需要时间长短) </li>
</ul>
</li>
<li>G1避免全堆扫描<ul>
<li>每个region中都有对应的rememberSet</li>
<li>jvm发现程序对reference类型进行写操作时，会暂时中断写，检查 reference是不是出于不同的Region之间(分代算法中就是检查老年代是否引用了新生代obj)，如果是就把信息记录到被引用的Region区域的RememberSet中，当GC Roots根节点枚举时，就把RememberSet加入到根节点就保证不会对整个堆扫描也不会有遗漏</li>
</ul>
</li>
<li>运行过程：<ul>
<li>初始标记<ul>
<li>stop-the-world，仅标注GC Roots能关联到的对象 </li>
</ul>
</li>
<li>并发标记<ul>
<li>可达性分析，能与用户线程并发 </li>
</ul>
</li>
<li>最终标记<ul>
<li>需要停顿线程，可并行执行 </li>
</ul>
</li>
<li>筛选回收<ul>
<li>根据用户设置停顿时间，最优回收 </li>
</ul>
</li>
</ul>
</li>
</ul>


                <hr>

                

                <ul class="pager">
                    
                        <li class="previous">
                            <a href="/myblog/2016/10/01/jvm/jvm执行/运行时栈帧结构/" data-toggle="tooltip" data-placement="top" title="jvm 运行时栈帧">&larr; Previous Post</a>
                        </li>
                    
                    
                        <li class="next">
                            <a href="/myblog/2016/10/01/jvm/jvm执行/class加载过程/" data-toggle="tooltip" data-placement="top" title="class加载过程">Next Post &rarr;</a>
                        </li>
                    
                </ul>

                

                
                <!-- disqus 评论框 start -->
                <div class="comment">
                    <div id="disqus_thread" class="disqus-thread"></div>
                </div>
                <!-- disqus 评论框 end -->
                

            </div>
    <!-- Side Catalog Container -->
        
            <div class="
                col-lg-2 col-lg-offset-0
                visible-lg-block
                sidebar-container
                catalog-container">
                <div class="side-catalog">
                    <hr class="hidden-sm hidden-xs">
                    <h5>
                        <a class="catalog-toggle" href="#">CATALOG</a>
                    </h5>
                    <ul class="catalog-body"></ul>
                </div>
            </div>
        

    <!-- Sidebar Container -->

            <div class="
                col-lg-8 col-lg-offset-2
                col-md-10 col-md-offset-1
                sidebar-container">

                <!-- Featured Tags -->
                
                <section>
                    <!-- no hr -->
                    <h5><a href="/myblog/tags/">FEATURED TAGS</a></h5>
                    <div class="tags">
                       
                          <a class="tag" href="/myblog/tags/#jvm" title="jvm">jvm</a>
                        
                          <a class="tag" href="/myblog/tags/#GC" title="GC">GC</a>
                        
                    </div>
                </section>
                

                <!-- Friends Blog -->
                
                <hr>
                <h5>FRIENDS</h5>
                <ul class="list-inline">

                    
                        <li><a href="http://blog.kaijun.rocks" target="_blank">Kaijun&#39;s Blog</a></li>
                    
                        <li><a href="http://huangxuan.me" target="_blank">Hux Blog</a></li>
                    
                        <li><a href="#" target="_blank">Foo</a></li>
                    
                        <li><a href="#" target="_blank">Bar</a></li>
                    
                        <li><a href="#" target="_blank">Example Friends</a></li>
                    
                        <li><a href="#" target="_blank">It helps SEO</a></li>
                    
                </ul>
                
            </div>

        </div>
    </div>
</article>




<!-- disqus 公共JS代码 start (一个网页只需插入一次) -->
<script type="text/javascript">
    /* * * CONFIGURATION VARIABLES * * */
    var disqus_shortname = "hexo-theme-huxblog";
    var disqus_identifier = "http://reflectyi.gitee.io/myblog/2016/10/01/jvm/memory/GC收集器7种/";
    var disqus_url = "http://reflectyi.gitee.io/myblog/2016/10/01/jvm/memory/GC收集器7种/";

    (function() {
        var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
        dsq.src = '//' + disqus_shortname + '.disqus.com/embed.js';
        (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
    })();
</script>
<!-- disqus 公共JS代码 end -->




<!-- async load function -->
<script>
    function async(u, c) {
      var d = document, t = 'script',
          o = d.createElement(t),
          s = d.getElementsByTagName(t)[0];
      o.src = u;
      if (c) { o.addEventListener('load', function (e) { c(null, e); }, false); }
      s.parentNode.insertBefore(o, s);
    }
</script>
<!-- anchor-js, Doc:http://bryanbraun.github.io/anchorjs/ -->
<script>
    async("https://cdn.bootcss.com/anchor-js/1.1.1/anchor.min.js",function(){
        anchors.options = {
          visible: 'always',
          placement: 'right',
          icon: '#'
        };
        anchors.add().remove('.intro-header h1').remove('.subheading').remove('.sidebar-container h5');
    })
</script>
<style>
    /* place left on bigger screen */
    @media all and (min-width: 800px) {
        .anchorjs-link{
            position: absolute;
            left: -0.75em;
            font-size: 1.1em;
            margin-top : -0.1em;
        }
    }
</style>



    <!-- Footer -->
    <!-- Footer -->
<footer>
    <div class="container">
        <div class="row">
            <div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1">
                <ul class="list-inline text-center">
                
                
                

                

                
                    <li>
                        <a target="_blank" href="https://www.facebook.com/stateInstance">
                            <span class="fa-stack fa-lg">
                                <i class="fa fa-circle fa-stack-2x"></i>
                                <i class="fa fa-facebook fa-stack-1x fa-inverse"></i>
                            </span>
                        </a>
                    </li>
                

                
                    <li>
                        <a target="_blank"  href="https://github.com/stateInstance">
                            <span class="fa-stack fa-lg">
                                <i class="fa fa-circle fa-stack-2x"></i>
                                <i class="fa fa-github fa-stack-1x fa-inverse"></i>
                            </span>
                        </a>
                    </li>
                

                

                </ul>
                <p class="copyright text-muted">
                    Copyright &copy; Hi,Ethan 2019 
                    <br>
                    Theme by <a href="http://huangxuan.me">Hux</a> 
                    <span style="display: inline-block; margin: 0 5px;">
                        <i class="fa fa-heart"></i>
                    </span> 
                    Ported by <a href="http://blog.kaijun.rocks">Kaijun</a> | 
                    <iframe
                        style="margin-left: 2px; margin-bottom:-5px;"
                        frameborder="0" scrolling="0" width="91px" height="20px"
                        src="https://ghbtns.com/github-btn.html?user=kaijun&repo=hexo-theme-huxblog&type=star&count=true" >
                    </iframe>
                </p>
            </div>
        </div>
    </div>
</footer>

<!-- jQuery -->
<script src="/myblog/js/jquery.min.js"></script>

<!-- Bootstrap Core JavaScript -->
<script src="/myblog/js/bootstrap.min.js"></script>

<!-- Custom Theme JavaScript -->
<script src="/myblog/js/hux-blog.min.js"></script>


<!-- async load function -->
<script>
    function async(u, c) {
      var d = document, t = 'script',
          o = d.createElement(t),
          s = d.getElementsByTagName(t)[0];
      o.src = u;
      if (c) { o.addEventListener('load', function (e) { c(null, e); }, false); }
      s.parentNode.insertBefore(o, s);
    }
</script>

<!-- 
     Because of the native support for backtick-style fenced code blocks 
     right within the Markdown is landed in Github Pages, 
     From V1.6, There is no need for Highlight.js, 
     so Huxblog drops it officially.

     - https://github.com/blog/2100-github-pages-now-faster-and-simpler-with-jekyll-3-0  
     - https://help.github.com/articles/creating-and-highlighting-code-blocks/    
-->
<!--
    <script>
        async("http://cdn.bootcss.com/highlight.js/8.6/highlight.min.js", function(){
            hljs.initHighlightingOnLoad();
        })
    </script>
    <link href="http://cdn.bootcss.com/highlight.js/8.6/styles/github.min.css" rel="stylesheet">
-->


<!-- jquery.tagcloud.js -->
<script>
    // only load tagcloud.js in tag.html
    if($('#tag_cloud').length !== 0){
        async("http://reflectyi.gitee.io/myblog/myblog/js/jquery.tagcloud.js",function(){
            $.fn.tagcloud.defaults = {
                //size: {start: 1, end: 1, unit: 'em'},
                color: {start: '#bbbbee', end: '#0085a1'},
            };
            $('#tag_cloud a').tagcloud();
        })
    }
</script>

<!--fastClick.js -->
<script>
    async("https://cdn.bootcss.com/fastclick/1.0.6/fastclick.min.js", function(){
        var $nav = document.querySelector("nav");
        if($nav) FastClick.attach($nav);
    })
</script>


<!-- Google Analytics -->


<script>
    // dynamic User by Hux
    var _gaId = 'UA-49627206-1';
    var _gaDomain = 'huangxuan.me';

    // Originial
    (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
    (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
    m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
    })(window,document,'script','//www.google-analytics.com/analytics.js','ga');

    ga('create', _gaId, _gaDomain);
    ga('send', 'pageview');
</script>




<!-- Baidu Tongji -->

<script>
    // dynamic User by Hux
    var _baId = '4cc1f2d8f3067386cc5cdb626a202900';

    // Originial
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "//hm.baidu.com/hm.js?" + _baId;
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
</script>


<!-- Side Catalog -->

<script type="text/javascript">
    function generateCatalog (selector) {
        var P = $('div.post-container'),a,n,t,l,i,c;
        a = P.find('h1,h2,h3,h4,h5,h6');
        a.each(function () {
            n = $(this).prop('tagName').toLowerCase();
            i = "#"+$(this).prop('id');
            t = $(this).text();
            c = $('<a href="'+i+'" rel="nofollow">'+t+'</a>');
            l = $('<li class="'+n+'_nav"></li>').append(c);
            $(selector).append(l);
        });
        return true;    
    }

    generateCatalog(".catalog-body");

    // toggle side catalog
    $(".catalog-toggle").click((function(e){
        e.preventDefault();
        $('.side-catalog').toggleClass("fold")
    }))

    /*
     * Doc: https://github.com/davist11/jQuery-One-Page-Nav
     * Fork by Hux to support padding
     */
    async("/myblog/js/jquery.nav.js", function () {
        $('.catalog-body').onePageNav({
            currentClass: "active",
            changeHash: !1,
            easing: "swing",
            filter: "",
            scrollSpeed: 700,
            scrollOffset: 0,
            scrollThreshold: .2,
            begin: null,
            end: null,
            scrollChange: null,
            padding: 80
        });
    });
</script>





<!-- Image to hack wechat -->
<img src="http://reflectyi.gitee.io/myblog/myblog/img/icon_wechat.png" width="0" height="0" />
<!-- Migrate from head to bottom, no longer block render and still work -->

</body>

</html>
